#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File    :   fast_test.py
@Time    :   2021/12/09 15:59:38
@Author  :   glx 
@Version :   1.0
@Contact :   18095542g@connect.polyu.hk
@Desc    :   None
"""

# here put the import lib
import numpy as np
from copy import deepcopy
import pandas as pd
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
from pathlib import Path
import math


def get_tan_rad(tan_value):
    # 计算反正切值（弧度）
    radians = math.atan(tan_value)
    # 将弧度转换为度
    degrees = math.degrees(radians)
    print(degrees)  #


def draw_line_pic(ts_sub_data):
    # 多项式拟合 x = ts_range, y = Freq

    fast_result = np.polyfit(ts_sub_data["ts_range"], ts_sub_data["Freq"], 1)
    plt.plot(ts_sub_data["ts_range"], ts_sub_data["Freq"], "o")
    plt.plot(
        ts_sub_data["ts_range"],
        fast_result[0] * ts_sub_data["ts_range"] + fast_result[1],
    )
    Path("fast_test_result").mkdir(parents=True, exist_ok=True)
    plt.savefig(rf"fast_test_result/fast_test_{ts_sub_data.index}.png")
    plt.close("all")
    # plt.show()


def do_fast_test(smooth_data, step, upper_rad, lower_rad, Freq_range):
    """
    Do adf test for all time series data
    input: smooth_data, step, upper_rad, lower_rad
    ST < Freq_range
    output: adf test result and p-value
    step = FAST_STEP,
    upper_rad = TAN_RANGE[1],
    lower_rad = TAN_RANGE[0],
    Freq_range = FAST_FREQ_RANGE
    test_result[key] = [bool]* len(smooth_data[key])
    """

    ts_data = {}
    test_result = {}

    key = "Freq"

    ts_data = smooth_data[[key, "ts_range"]]
    result_list = []
    # 拆分为子段
    ts_data_list = []
    ts_data_length = len(ts_data)
    start = 0
    while start < ts_data_length:
        ts_data_list.append(ts_data.iloc[start : start + step, :])
        start += step

    for ts_sub_data in ts_data_list:
        # print(ts_sub_data.head())
        length = len(ts_sub_data)
        # TODO change index from range to fixed time stamp(4 second as the scale)
        # print(ts_sub_data["Freq"])
        # print(ts_sub_data["ts_range"])

        ## 文件data\json_data\信号169255样本数据.json
        ## 这里收到的数据是40s一个，所以横轴需要扩张
        fast_result = np.polyfit(ts_sub_data["ts_range"], ts_sub_data["Freq"], 1)
        if len(ts_sub_data["ts_range"]) < 50:
            print(length)
        # 存储子段的fast检验结果, 起点,终点
        # 检验策略:
        # 1. 如果k在斜率范围之间 则认为通过检验
        # 2. 如果极差大于Freq_range,则不通过检验
        # k,b = np.polyfit(smooth_data["station"], np.arange(len(smooth_data["station"])), 1)

        """ 
        step = FAST_STEP,
        upper_rad = TAN_RANGE[1],
        lower_rad = TAN_RANGE[0],
        Freq_range = FAST_FREQ_RANGE 
        """
        low, up = np.tan(np.deg2rad(lower_rad)), np.tan(np.deg2rad(upper_rad))

        big, small = max(ts_sub_data[key]), min(ts_sub_data[key])

        # DEBUG
        # draw_line_pic(ts_sub_data)

        # 斜率在范围内，频差Freq_range太大也不算高速应该算机动 # TODO check if true
        # print(get_tan_rad(fast_result[0]))
        # if low < abs(fast_result[0]) < up and (big - small) < Freq_range:
        #     real_result = True

        if low < abs(fast_result[0]) < up:
            real_result = True
        else:
            real_result = False
        result_list.append((real_result, ts_sub_data.index[0], ts_sub_data.index[-1]))

    test_result[key] = result_list
    stable_data = deepcopy(smooth_data)
    for key in test_result.keys():
        result_list = test_result[key]
        for result in result_list:
            if not result[0]:
                stable_data[key].drop(
                    index=range(result[1], result[2] + 1), inplace=True
                )

    return test_result[key], stable_data
